package io.gitee.hchaojie.day07;

import org.junit.Test;

import java.io.*;

public class TestReader {
    @Test
    public void test() {
        try (InputStream in = new FileInputStream("data\\中文.txt")) {
            byte[] bytes = new byte[4];
            in.read(bytes);

            System.out.println(new String(bytes));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test1() {
        // 文件编码是gbk
        // 1. 如果代码的编码是gbk，文件可以正常读取
        // 2. 如果代码是utf-8编码，文件读取出错
        try (InputStreamReader reader = new FileReader("data\\中文.txt")) {
            int c;

            while ((c = reader.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2() {
        // 使用指定的编码读取文件

        try (
                // 字节流
                InputStream in = new FileInputStream("data\\chinese-utf8.txt");
                // 使用指定的编码，把字节流转化成字符流
                InputStreamReader reader = new InputStreamReader(in, "utf-8");
        ) {
            int c;

            while ((c = reader.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test3() throws UnsupportedEncodingException {
        // 使用指定的编码读取文件
        // 字节流
        // 使用指定的编码，把字节流转化成字符流

        String s = new String("data\\中文.txt".getBytes(), "gbk");
        try (InputStream in = new FileInputStream(s)) {
            try (InputStreamReader reader = new InputStreamReader(in, "gbk")) {
                int c;

                while ((c = reader.read()) != -1) {
                    System.out.print((char) c);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Test
    public void test4() throws UnsupportedEncodingException {
        // String s = new String("data\\中文.txt".getBytes("gbk"));

        // 中文名的文件，打开的时候，需要使用gbk对文件名进行编码
        String fileName = new String("中文.txt".getBytes("gbk"));
        System.out.println(new File(fileName).exists());  // true

        fileName = new String("中文.txt".getBytes("utf-8"));
        System.out.println(new File(fileName).exists());  // false
    }
}
